package cn.xz.mytimer

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.NumberPicker
import java.lang.reflect.Field


class TimeNumberPicker : NumberPicker {
    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    override fun addView(child: View, params: ViewGroup.LayoutParams) {
        this.addView(child, 0, params)
    }

    override fun addView(child: View, index: Int, params: ViewGroup.LayoutParams) {
        super.addView(child, index, params)
        updateView(child)
    }

    private fun updateView(view: View) {
        if (view is EditText) {
            //设置通用(默认)文字的颜色和大小
            view.setTextColor(Color.parseColor("#FFFFFF"))
            view.textSize = 32f
        }
        try {
            //设置分割线大小颜色
            val mSelectionDivider = getFile("mSelectionDivider")
            if (mSelectionDivider != null){
                mSelectionDivider[this] = ColorDrawable(Color.parseColor("#33FFFFFF"))
                mSelectionDivider[this] = 1
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //反射获取控件 mSelectionDivider mInputText当前选择的view
    private fun getFile(fieldName: String?): Field? {
        try {
            //设置分割线的颜色值
            val pickerFields = NumberPicker::class.java.getDeclaredField(fieldName)
            pickerFields.isAccessible = true
            return pickerFields
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    //设置选中控件的style  注意一点要在setOnValueChangedListener或 setOnScrollChangeListener,setOnScrollListener中调
    // 用picker.performClick();两种情况动画效果不同
    //同时注意他的代用位置 要在当前控件初始化之后 否则获得不了
    fun setMInputStyle(size: Float?) {
        val mInputText = getFile("mInputText")
        try {
            (mInputText!![this] as EditText).textSize = size!!
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
    }
}
